<?php

class LoginValidator extends sfValidatorSchema
{
  public function __construct($options = array(), $messages = array())
  {
    parent::__construct(null, $options, $messages);
  }
  
  protected function configure($options = array(), $messages = array())
  {
    $this->addRequiredOption('model');
    $this->addRequiredOption('column');
    $this->addRequiredOption('find_method');

    $this->addMessage('no_profile'    , 'Tu cuenta no tiene un perfil definido. Por favor contactese con el administrador de este site');
    $this->addMessage('inactive'      , 'Tu cuenta esta actualmente inactiva. Por favor contactese con el administrador de este site');
    $this->addMessage('wrong_password', 'Tu password no coincide con en el la BD.');
    $this->setMessage('invalid'       , '"%column%" incorrecto.');
  }
  
  protected function doClean($values)
  {
    if (!is_array($values))
    {
      throw new InvalidArgumentException('You must pass an array parameter to the clean() method (this validator can only be used as a post validator).');
    }
    
    if (!is_array($this->getOption('column')))
    {
      $this->setOption('column', array($this->getOption('column')));
    }
    
    // not validate when any field is blank
    foreach ($values as $value)
    {
      if (empty($value)) return $values;
    }
    
    $columns    = $this->getOption('column');
    $findMethod = $this->getOption('find_method');
    $user       = Doctrine::getTable($this->getOption('model'))->$findMethod($values[$columns[0]]);
    
    $arguments = array();
    if (!$user)
    {
      $error     = 'invalid';
      $arguments = array('column' => implode(', ', $this->getOption('column')));
    }
    elseif (kcCipher::getInstance()->encrypt($values[$columns[1]]) != $user->getPassword())
    {
      $error     = 'wrong_password';
    }
    elseif (!$user->getPerfil()->exists())
    {
      $error     = 'no_profile';
    }
    elseif (!$user->isActive())
    {
      $error     = 'inactive';
    }
    else
    {
      return $values;
    }
    
    $error = new sfValidatorError($this, $error, $arguments);
    
    throw $error;
  }
}
